package org.example.comment.interception;

import io.netty.util.internal.StringUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.example.comment.utils.ThreadLocalUtil;
import org.example.constant.MessageConstant;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;


@Slf4j
@Component
public class UserInfoInterception implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 获取请求头中的用户信息
        String userInfo = request.getHeader(MessageConstant.HEADER_NAME);
        // 不能为空也不能为null，否则会报空指针异常
        if(StringUtil.isNullOrEmpty(userInfo)){
            log.info("HandlerInterceptor-用户信息为：{}",userInfo);
//            response.setStatus(401);
            return true;
        }
        ThreadLocalUtil.set(userInfo);
        log.info("HandlerInterceptor-用户信息为：{}",userInfo);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        // 清除用户信息
        ThreadLocalUtil.remove();
    }
}
